const path = require('path');
const fs = require('fs');
/**
 * @param {string} fpath 
 */
const resolve = (fpath) => path.resolve(process.cwd(), fpath);
const envDefinePath = resolve('domain/domain.env.js');
const shouldReplaceEnv = fs.existsSync(envDefinePath);

/**
 * 替换环境变量
 * @param {string} source 
 */
module.exports = function replaceEnv(source) {
  let newSource = source;
  if (shouldReplaceEnv) {
    const reactModules = require(envDefinePath);
    newSource = newSource.replace(/process\.env\.(\w+)/g, (_, $1) => {
      const modulePath = reactModules['process.env'][$1] ? reactModules['process.env'][$1] : _;
      return modulePath;
    });
  }
  return newSource;
}